<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/2/13
 * Time: 14:33
 */

namespace app\admin\controller;

//活动报名人员管理controller
use app\admin\model\Active;
use app\admin\model\ChannelList;
use app\admin\model\ContestantNumber;
use app\admin\model\VoteList;
use Library\Object_Id;
use think\Config;
use app\admin\model\Participant as AdminModel;
use think\Loader;

class Participant extends Admin
{
    protected $code_name = '报名人员';

    public function set_param()
    {
        parent::set_param(); // TODO: Change the autogenerated stub
        $this->assign('code_name',$this->code_name);
        $this->assign('code','participant');
        $this->admin_model = new AdminModel();
    }

    public function after_read_model()
    {
        $active_id = $this->request->param('active_id');
        $active_end_time = 0;
        if($active_id){
            $active_end_time = Active::where('id',$active_id)->value('end_at');
            $this->assign('active_id',$active_id);
        }else if($this->admin_model){
            $active_end_time = Active::where('id',$this->admin_model->active_id)->value('end_at');
            $this->assign('active_id',$this->admin_model->active_id);
        }

        $now_time = time();
        $is_open = ($now_time>$active_end_time)?0:1;
        $this->assign('is_open',$is_open);
        $this->assign('channels',ChannelList::column('channel_name','id'));
    }

    public function index(){
        $params = $this->request->param();
        if(empty($params['active_id'])){
            $this->error('活动id丢失');
        }
        $active_id = $params['active_id'];
        $search_type = empty($params['search_type'])?'':$params['search_type'];
        $keywords = empty($params['keywords'])?'':$params['keywords'];
        $order_field = empty($params['order_field'])?'create_time':$params['order_field'];
        $order_type = empty($params['order_type'])?'desc':$params['order_type'];
        $search_status = false;
        $search_channel = false;

        if(isset($params['search_status']) && is_numeric($params['search_status'])){
            $search_status = $params['search_status'];
        }
        if(isset($params['search_channel']) && is_numeric($params['search_channel'])){
            $search_channel = $params['search_channel'];
        }
        $where['active_id'] = $active_id;
        if($keywords){
            if($search_type != 'contestant_number'){
                $where[$search_type] = ['like','%'.$keywords.'%'];
            }else{
                $where[$search_type] = ['=',$keywords];
            }
        }
        if($search_status !== false){
            $where['status'] = ['=',$search_status];
        }
        if($search_channel !== false){
            $where['channel'] = ['=',$search_channel];
        }
        $order = $order_field.' '.$order_type;
        $query = [
            'active_id'=>$active_id,
            'search_type'=>$search_type,
            'keywords'=>$keywords,
            'order_field'=>$order_field,
            'order_type'=>$order_type,
            'search_status'=>$search_status?$search_status:'all',
            'search_channel'=>$search_channel?$search_channel:'all'
        ];
        $list = $this->admin_model->where($where)->order($order)->paginate(10,false,['query'=>$query]);
        $active_name = Active::where('id',$active_id)->value('name');
        $active_end_time = Active::where('id',$active_id)->value('end_at');
        $now_time = time();
        $is_open = ($now_time>$active_end_time)?0:1;

        return view('',[
            'list'=>$list,
            'page'=>$list->render(),
            'active_name'=>$active_name,
            'active_id'=>$active_id,
            'search_status'=>$search_status,
            'search_channel'=>$search_channel,
            'search_type'=>$search_type,
            'keywords'=>$keywords,
            'order_field'=>$order_field,
            'order_type'=>$order_type,
            'is_open'=>$is_open,
            'pass_way'=>Config::get('pass_way'),
            'sites'=>Config::get('site'),
            'channels'=>ChannelList::column('channel_name','id')
        ]);
    }

    public function create($post)
    {
        if(empty($post['nickname'])){
            return json(['code'=>199,'message'=>'昵称不能为空']);
        }
        if(empty($post['audio_url'])){
            //return json(['code'=>199,'message'=>'上传音频不能为空']);
        }
        $images = [];
        $cover = '';
        $timestamp = date('Y-m-d H:i:s');



        if(empty($post['cover'])){
            if(empty($post['images'])){
                return json(['code'=>199,'message'=>'上传图片不能为空']);
            }else{

                foreach($post['images'] as $img){
                    $images[] = $this->request->domain().$img;
                    // $params = [
                    //     'bucket'=>'',
                    //     'object'=>substr($img,1),
                    //     'path'=>$this->request->domain().$img,
                    //     'caller'=>'vote',
                    //     'timestamp'=>$timestamp
                    // ];

                    // $sign = create_sign($params,'');//oss上传sign生成key;
                    // $params['sign'] = $sign;
                    // $res = $this->getImgUrl($params);
                    // if($res){
                    //     $images[] = $res;
                    // }
                }
            }

        // var_dump($images);
        // exit();

        }else{
            $cover = $post['cover'];
            $images[] = $post['cover'];
        }

        //获取选手编号模型
        $model = ContestantNumber::where('active_id',$post['active_id'])->find();

        //添加记录
        $obj = new Object_Id();
        $participant_model = new AdminModel();
        $participant_model->autoWriteTimestamp = false;
        $participant_model->create([
            'active_id'=>$post['active_id'],
            'user_id'=>$obj->get_new_id(),
            'sign_pass_way'=>'backend',
            'nickname'=>$post['nickname'],
            'mobile'=>$post['mobile']?$post['mobile']:'后台添加',
           // 'birthday'=>$post['birthday'],
            'xuanyan'=>$post['xuanyan'],
            'shop_name'        =>$post['shop_name'],
            'shop_address'     =>$post['shop_address'],
            'shop_introduction'=>$post['shop_introduction'],
            'status'=>$post['status'],
            'gender'=>$post['gender'],
            'images'=>$images,
            'images2'=>!empty($cover) ? $cover : $post['images'][0],
            'channel'=>0,
            'cover'=>$cover,
            'contestant_number'=>$model?$model->number:0,
            'audio_url'=>empty($post['audio_url'])?'':$post['audio_url'],
            'audio_time'=>empty($post['audio_time'])?'':$post['audio_time'],
            'create_time'=>time(),
            'update_time'=>time()
        ]);

        if($model){
            //更新选手编号
            ContestantNumber::where('active_id',$post['active_id'])->setInc('number', rand(1,3));
        }
        return json(['code'=>0,'message'=>'报名成功']);
    }

    public function update($post){
        if(empty($post['images'])){
            //return json(['code'=>199,'message'=>'上传图片不能为空']);
        }

        $images = [];
        $cover = '';
        $timestamp = date('Y-m-d H:i:s');

        if(empty($post['cover'])){
            if(empty($post['images'])){
                return json(['code'=>199,'message'=>'上传图片不能为空']);
            }else{
                // foreach($post['images'] as $img){
                //     $images[] = $this->request->domain().$img;
                // }
            }

        
        $this->admin_model->cover       = $post['images'];
        $this->admin_model->images      = $post['images'];

        }

        // $participant_model = new AdminModel();
        // $participant_model->autoWriteTimestamp = false;

        // $user_edit = array(
        //     'nickname'=>$post['nickname'],
        //     'mobile'=>$post['mobile']?$post['mobile']:'后台添加',
        //     'birthday'=>$post['birthday'],
        //     'xuanyan'=>$post['xuanyan'],

        //     'gender'=>$post['gender'],

        //     'update_time'=>time()
        // );
 
        $update = array(
            'nickname'    => isset($post['nickname']) ? $post['nickname']  : "",
            'mobile'      => isset($post['mobile'])   ? $post['mobile']    : "",
            //'birthday' => isset($post['birthday']) ? $post['birthday']  : "",
            'body_height' => isset($post['body_height']) ? $post['body_height'] : "",
            'specialty'   => isset($post['specialty'])   ? $post['specialty']   : "",
            'xuanyan'     => isset($post['xuanyan'])     ? $post['xuanyan']     : "",
            'shop_name'      => isset($post['shop_name'])         ? $post['shop_name']      : "",
            'shop_address'      => isset($post['shop_address'])         ? $post['shop_address']      : "",
            'shop_introduction' => isset($post['shop_introduction'])    ? $post['shop_introduction'] : "",
            'gender'      => isset($post['gender'])      ? $post['gender']      : "",
            'update_time' =>time()
        );

        foreach($update as $key=>$val){
            $this->admin_model->$key = $val;
        }

        // $this->admin_model->mobile      = $post['mobile']?$post['mobile']:'后台添加';
        // $this->admin_model->birthday    = $post['birthday'];
        // $this->admin_model->xuanyan     = $post['xuanyan'];
        // $this->admin_model->gender      = $post['gender'];
        $this->admin_model->update_time = time();
       //);

        $this->admin_model->status = $post['status'];
        $this->admin_model->images = empty($post['images'])?[]:$post['images'];
        $this->admin_model->images2 = empty($post['cover'])?$post['images'][0]:$post['cover'];
        $this->admin_model->no_pass_intro = $post['no_pass_intro'];
        $this->admin_model->save();
        return json(['code'=>0,'message'=>'修改成功,即将跳转报名人列表']);
    }

    public function set_cover(){
        $param = $this->request->param();
        $this->admin_model->where('id',$param['id'])->update(['cover'=>$param['img']]);
        $this->admin_model->where('id',$param['id'])->update(['images2'=>$param['img']]);
        return json(['code'=>0,'message'=>'设置封面成功']);
    }

    public function cancel(){
        $this->admin_model->where('id',$this->request->param('id'))->update(['status'=>2]);

        return json(['code'=>0,'message'=>'已禁用']);
    }

    public function total_number(){
        $participant_model = $this->admin_model->where('id',$this->request->param('id'))->find();
        if($participant_model){
            $res = VoteList::field('count(*) as number,from_pass_way')->where('participant_id',$participant_model->user_id)->where('active_id',$participant_model->active_id)->where('status',1)->group('from_pass_way')->select();
            //print_r($res);die;
            $weight = Active::where('id',$participant_model->active_id)->value('weight');
            $weight = json_decode($weight);
            $yqsbz = $wx = $support = 0;
            if($res){
                foreach($res as $item){
                    if($item->from_pass_way == 'yqsbz'){
                        $yqsbz = $item->number;
                    }elseif($item->from_pass_way == 'wx'){
                        $wx = $item->number;
                    }
                }
            }
            $participant_model->pass_way_yqsbz = $yqsbz;
            $participant_model->pass_way_wx = $wx;
            $participant_model->support = $wx*$weight->wx + $yqsbz*$weight->yqsbz;
            $participant_model->save();
            return json(['code'=>0,'message'=>'重新统计成功']);
        }
        return json(['code'=>199,'message'=>'找不到对应的参赛者']);
    }


    //获取图片,原理是将本地图片上传并获得阿里云oss上的图片地址
    private function getImgUrl($params){

        $erpUrl = "";
        $rtjson = $this->getCurlData($erpUrl,2,$params);

        $rtarr = json_decode($rtjson,true);
        //print_r($rtarr)
        if($rtarr['result']['success'] == 1){
            return $rtarr['items']['path'];
        }else{
            return 0;
        }
    }



    //curl访问自己公司的接口,有修改,这里是post访问
    private function getCurlData($url,$dotype,$post_data){
        $get = '';
        if($dotype==1){
            $get =file_get_contents($url);
        }elseif($dotype==2){
            $ch = curl_init() or die (curl_error());
            curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            //设置post访问
            curl_setopt($ch, CURLOPT_POST, 1);
            // post的变量
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);//响应时间
            $get = curl_exec($ch);
            curl_close($ch);
        }
        return $get;
    }

    public function to_excel(){

        $active_id = $this->request->param('active_id');
        if(!$active_id){
            $this->error('活动id丢失');
        }

        $active_name = Active::where('id',$active_id)->value('name');
        require_once VENDOR_PATH . 'PHPExcel.php';
        $objPHPExcel = new \PHPExcel();


        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '用户编号')
            ->setCellValue('B1', '得票总数')
            ->setCellValue('C1', '用户昵称')
            ->setCellValue('D1', '用户手机')
            ->setCellValue('E1', '参加渠道')
            ->setCellValue('F1', '用户生日')
            ->setCellValue('G1', '微信得票')
            ->setCellValue('H1', '上班族得票')
            ->setCellValue('I1', '参赛宣言')
            ->setCellValue('J1', '参加时间')
            ;

        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setAutoSize(true);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle($active_name.'-活动人员表');

        $list = $this->admin_model->where('active_id',$active_id)->where('status',1)->order('support desc')->select();

        if($list){
            $pass_way = Config::get('pass_way');
            // Set active sheet index to the first sheet, so Excel opens this as the first sheet
            foreach($list as $key=>$value){
                $key +=2;
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$key, $value->contestant_number)
                    ->setCellValue('B'.$key, $value->support)
                    ->setCellValue('C'.$key, $value->nickname)
                    ->setCellValue('D'.$key, $value->mobile)
                    ->setCellValue('E'.$key, $pass_way[$value->sign_pass_way])
                    ->setCellValue('F'.$key, $value->birthday)
                    ->setCellValue('G'.$key, $value->pass_way_wx)
                    ->setCellValue('H'.$key, $value->pass_way_yqsbz)
                    ->setCellValue('I'.$key, $value->xuanyan)
                    ->setCellValue('J'.$key, date('Y-m-d H:i:s',$value->create_time));
            }

        }


        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$active_name.'-活动人员表.xls"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}